package com.example.demo.config;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.constants.RedisKey;
import com.example.demo.domain.entity.Company;
import com.example.demo.domain.entity.PermissionUrl;
import com.example.demo.domain.entity.RolePermission;
import com.example.demo.domain.entity.UserRole;
import com.example.demo.domain.entity.VojProblemTags;
import com.example.demo.mapper.CompanyMapper;
import com.example.demo.mapper.PermissionFrontUrlMapper;
import com.example.demo.mapper.PermissionUrlMapper;
import com.example.demo.mapper.RolePermissionMapper;
import com.example.demo.mapper.UserRoleMapper;
import com.example.demo.mapper.VojProblemTagsMapper;
import com.example.demo.utils.RedisUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 初始化数据
 */
@Component
public class InitDataConfig implements InitializingBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        initRoleCompany();
        initCompanyIdName();
        initTagIdName();
        sysSwitch();
        initRolePermission();
    }

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private CompanyMapper companyMapper;
    @Resource
    private VojProblemTagsMapper tagsMapper;

    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @Resource
    private PermissionFrontUrlMapper permissionFrontUrlMapper;

    @Resource
    private PermissionUrlMapper permissionUrlMapper;

    /**
     * 初始化角色id - 公司id
     */
    private void initRoleCompany(){
        List<UserRole> userRoles = userRoleMapper.selectList(new QueryWrapper<>());
        if (CollectionUtil.isEmpty(userRoles)){
            return ;
        }
        Map<Long, Long> collect = userRoles.stream().collect(Collectors.toMap(UserRole::getId, UserRole::getCId));
        redisUtil.setMap(RedisKey.ROLE_COMPANY, collect);
    }

    /**
     * 初始化公司id - 公司名称
     */
    private void initCompanyIdName(){
        List<Company> companies = companyMapper.selectList(new QueryWrapper<>());
        if (CollectionUtil.isEmpty(companies)){
            return ;
        }
        Map<Long, String> collect = companies.stream().collect(Collectors.toMap(Company::getId, Company::getName));
        redisUtil.setMap(RedisKey.COMPANY_ID_NAME, collect);
    }
    /**
     * 初始化标签id - 标签名称
     */
    private void initTagIdName(){
        List<VojProblemTags> tagList = tagsMapper.selectList(new QueryWrapper<>());
        if (CollectionUtil.isEmpty(tagList)){
            return ;
        }
        Map<Long, String> collect = tagList.stream().collect(Collectors.toMap(VojProblemTags::getProblemTagId, VojProblemTags::getProblemTagName));
        redisUtil.setMap(RedisKey.TAG_ID_NAME, collect);
    }


    /**
     * 初始化系统开关
     */
    private void sysSwitch(){
        redisUtil.setKey(RedisKey.SYS_SWITCH, "1");
    }


    /**
     * 初始化系统权限
     */
    private void initRolePermission(){
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<UserRole>();
        List<UserRole> userRoles = userRoleMapper.selectList(queryWrapper);

        List<Long> roleIds = new ArrayList<>();
        for (UserRole userRole : userRoles) {
            if (!roleIds.contains(userRole.getId())){
                roleIds.add(userRole.getId());
            }
        }

        if (!CollectionUtil.isEmpty(roleIds)){
            Map<Long,List<Long>> roleFrontIdMap = new HashMap<>(roleIds.size());
            QueryWrapper<RolePermission> queryWrapper1 = new QueryWrapper<RolePermission>();
            for (Long roleId : roleIds) {
                queryWrapper1.clear();
                queryWrapper1.eq("role_id",roleId);
                List<RolePermission> rolePermissions = rolePermissionMapper.selectList(queryWrapper1);
                if (!CollectionUtil.isEmpty(rolePermissions)){
                    List<Long> roleFrontIds = new ArrayList<>();
                    for (RolePermission rolePermission : rolePermissions) {
                        roleFrontIds.add(rolePermission.getfId());
                    }
                    roleFrontIdMap.put(roleId,roleFrontIds);
                }
            }

            // 存redis
            for (Long aLong : roleFrontIdMap.keySet()) {
                QueryWrapper<PermissionUrl> queryWrapper2 = new QueryWrapper<PermissionUrl>();
                if (!CollectionUtil.isEmpty(roleFrontIdMap.get(aLong))){
                    queryWrapper2.clear();
                    queryWrapper2.in("f_id",roleFrontIdMap.get(aLong));
                    List<PermissionUrl> permissionUrls = permissionUrlMapper.selectList(queryWrapper2);
                    if (!CollectionUtil.isEmpty(permissionUrls)){
                        List<String> strings = new ArrayList<>();
                        for (PermissionUrl permissionUrl : permissionUrls) {
                            if (!strings.contains(permissionUrl.getBackUrl())){
                                strings.add(permissionUrl.getBackUrl());
                            }
                        }
                        redisUtil.delKey(RedisKey.REDIS_PERMISSION_BACK_URL_SET.concat(String.valueOf(aLong)));
                        redisUtil.setKeyOfList(RedisKey.REDIS_PERMISSION_BACK_URL_SET.concat(String.valueOf(aLong)),strings);
                    }
                }
            }
        }
    }

}

